import request from './request';

// http常用请求头
const REQUEST_HEADERS = {
  'json': 'application/json; charset=UTF-8',
  'form': 'application/x-www-form-urlencoded; charset=UTF-8',
  'file': 'multipart/form-data'
};

// http头判断
function getHeader4Data(dataType: string) {
  dataType = dataType || 'json';
  const headers = {
    'X-Requested-With': 'XMLHttpRequest',
    // @ts-ignore
    'Content-Type': REQUEST_HEADERS[dataType]
  };
  return headers;
}

/* form表单参数转换 */
function parseUrlFormParam(obj: any) {
  obj = obj || {};
  const pairs: Array<string> = [];
  Object.keys(obj).forEach((key) => {
    let value = obj[key];
    if (!value && (value === null || value === undefined || isNaN(value))) {
      value = '';
    }
    pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  });
  return pairs.length ? pairs.join('&') : '';
}

/* get */
function get(url: string, params: any) {
  if (!params) {
    params = {};
  }
  return request({ method: 'get', url, params, timeout: 10000, headers: { 'X-Requested-With': 'XMLHttpRequest' } });
}

/* post 入口 */
function post(url: string, data: any, dataType: string, timeout = 10000) {
  const headers = getHeader4Data(dataType);
  data = dataType === 'form' ? parseUrlFormParam(data) : dataType === 'file' ? data : data;
  return request({ method: 'post', url, data: data, timeout: timeout, headers });
}

/* 输出 */
export default {
  get,
  postJson(url: string, params: any) {
    return post(url, params, "");
  },
  postForm(url: string, params: any) {
    return post(url, params, 'form');
  },
  postFile(url: string, params: any) {
    return post(url, params, 'file', 15000);
  }
};
